#!/bin/bash
### BEGIN INIT INFO
# Provides:          pocp-xml-rpc
# Required-Start:    $local_fs $network $syslog postgresql
# Required-Stop:     $local_fs $network $syslog postgresql
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: Start/stop opencaptiveportal XML-RPC daemon
### END INIT INFO

# This init.d Script is to start the XML RPC daemon

. /lib/lsb/init-functions

# Only as root executable
if [ $UID != 0 ]; then
  echo "Error: $0 must be executed as user root!"
  exit 2
fi

# Configuration
DESC="Open Captive Portal XML-RPC Daemon"
NAME="xml-rpc-server.py"
PIDFILE=/var/run/pocp-xml-rpc.pid

start() {
  # Environment for XML-RPC daemon
  cd /usr/local/pocp/
  log_daemon_msg "Starting $DESC" "$NAME"
  sudo -u www-data sh -c "DJANGO_SETTINGS_MODULE='pocp.settings' python ./xml-rpc-server.py" &
  mpid="$!"

  if ps -p "$mpid" > /dev/null 2>&1; then
    echo "$mpid" > $PIDFILE
    log_end_msg 0
  else
    log_failure_msg "check syslog for diagnostics."
    log_end_msg 1
  fi
}

stop() {
  log_daemon_msg "Stopping $DESC" "$NAME"
  start-stop-daemon --stop --quiet --pidfile $PIDFILE
  log_end_msg $?
  rm -f "$PIDFILE"
}


if [ "$1" == "start" ]; then
  start
elif [ "$1" == "stop" ]; then
  stop
elif [ "$1" == "restart" ]; then
  stop || true
  sleep 1
  start
else 
  echo "Usage: $0 [ start | stop | restart ]"
  exit 9
fi

